<?php

/**
 * This file is part of the Codizer package.
 *
 * For the full copyright and license information, please view the LICENSE
 * file that was distributed with this source code.
 *
 * @copyright   Copyright (c) 2010 Advisa (http://www.advisa.fr)
 * @author      Codizer Core Team <team@codizer.org>
 * @package     Codizer
 */

/**
 * Check if the current user has right to launch the code between the tags. For this the current user context is used (f_context_User)
 *
 * SEE function.hasRightElse.php FOR ELSE CONDITION !
 *
 * @param rule : the rule to check if user has right or not (in myModule/config/rights.xml)
 *
 * @example : {hasRight rule="news_display"}<h1>My title</h1><p>some news</p>{/hasRight}
 */
function smarty_block_hasRight($params, $content, &$smarty, &$repeat)
{		
	if($params['rule'] != "")
	{
		$rules = explode(" ", $params['rule']);
		$ok = false;

        $context = isset($params["context"]) ? $params["context"] : "";
        $userContext = f_context_User::getInstance($context);

        $else = $smarty->left_delimiter . 'hasRightElse' . $smarty->right_delimiter;

        $trueFalse = explode($else, $content, 2);

        $true = (isset($trueFalse[0]) ? $trueFalse[0] : null);
        $false = (isset($trueFalse[1]) ? $trueFalse[1] : null);

		foreach($rules as $rule)
		{
			//if the user has the right
			if($userContext->hasRight($rule) == true)
			{
				$ok = true;
			}
			
			//if it's the current user
			if(!is_null($userContext->getUser()) && $rule == $userContext->getUser()->getUniqueId())
			{
				$ok = true;
			}

            //if user is connected
            if($rule == "connected" && !is_null($userContext->getUser()))
            {
                $ok = true;
            }
		}
		
		return ($ok == true) ? $true : $false;
	}
	else
	{		
		return $content;
	}
}